package com.zpark.mq.t2.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * 连接工具类
 * 返回连接对象
 */
public class RabbitConnectionUtil {

    /**
     * 获取建立TCP连接
     * @param host ip地址
     * @param uname 用户名
     * @param pwd 密码
     * @param port 端口号
     * @param virtualHost 虚拟主机名字
     * @return 连接对象
     */
    public final static Connection getConnection(String host, String uname, String pwd,
                                                int port, String virtualHost){
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置连接信息
        factory.setHost(host);
        factory.setUsername(uname);
        factory.setPassword(pwd);
        factory.setPort(port);

        // 设置MQ虚拟主机
        factory.setVirtualHost(virtualHost);
        Connection conn = null;

        try {
            conn = factory.newConnection();
        } catch(Exception e) {
            System.err.println("获取连接失败");
        }

        return conn;
    }

    /**
     * 关闭连接
     * @param conn tcp连接对象
     * @param channel 通道连接对象
     */
    public final static void close(Connection conn, Channel channel) throws Exception{
        if (channel != null) {
            channel.close();
        }

        if (conn != null) {
            conn.close();
        }
    }
}
